package com.liuxin.zhiyuan.shujuzhongxin.task;

import com.liuxin.zhiyuan.shujuzhongxin.domain.po.HistoricalAdmissionScoreEntity;
import com.liuxin.zhiyuan.shujuzhongxin.domain.po.RecruitMajorInfoEntity;
import com.liuxin.zhiyuan.shujuzhongxin.service.HistoricalAdmissionScoreService;
import com.liuxin.zhiyuan.shujuzhongxin.service.RecruitMajorInfoService;
import com.liuxin.zhiyuan.shujuzhongxin.service.ScoreSegmentService;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 招生专业信息定时任务
 * 计算预测排名和预测分数
 */
@Component
public class RecruitMajorInfoTask {

    private static final Logger logger = LoggerFactory.getLogger(RecruitMajorInfoTask.class);

    @Autowired
    private RecruitMajorInfoService recruitMajorInfoService;

    @Autowired
    private HistoricalAdmissionScoreService historicalAdmissionScoreService;

    @Autowired
    private ScoreSegmentService scoreSegmentService;

    @PostConstruct
    public void initCalculatePrediction() {
        logger.info("应用启动，开始执行招生专业信息预测排名和分数计算任务");
        calculatePrediction();
    }


    /**
     * 每天凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void calculatePrediction() {
        logger.info("开始执行招生专业信息预测排名和分数计算任务");
        try {
            // 获取未处理的记录
            List<RecruitMajorInfoEntity> unprocessedRecords = recruitMajorInfoService.getUnprocessedRecords();
            // 查询出10条需要处理的数据
            if (CollectionUtils.isEmpty(unprocessedRecords)) {
                logger.info("没有需要处理的记录");
                return;
            }
            logger.info("找到{}条未处理记录", unprocessedRecords.size());
            // 处理每条记录
            List<RecruitMajorInfoEntity> toUpdateRecords = new ArrayList<>();
            for (RecruitMajorInfoEntity record : unprocessedRecords) {
                try {

                    String nature = getWenLi(record);
                    // 根据school_id和pro查询历史录取分数
                    List<HistoricalAdmissionScoreEntity> historicalScores =
                            historicalAdmissionScoreService.findBySchoolIdAndPro(record.getSchoolId(), record.getPro(),nature);
                    Integer avgRank = null;
                    Integer score = null;

                    if (CollectionUtils.isEmpty(historicalScores)) {
                        // 计算专业组平均排名
                        avgRank = calculateSchoolCodeAverageRank(record,nature);
                        if (avgRank == null) {
                            logger.warn("无法计算学校ID为{}，专业为{}的专业组平均排名", record.getSchoolId(), record.getPro());
                            continue;
                        }
                    }else{
                        // 计算位次平均值
                        avgRank = calculateAverageRank(historicalScores);
                        if (avgRank == null) {
                            logger.warn("无法计算学校ID为{}，专业为{}的平均位次", record.getSchoolId(), record.getPro());
                            continue;
                        }
                    }
                    // 根据位次查询对应的分数
                    String subjectType = getSubjectType(record);
                    score = scoreSegmentService.findScoreByRank("2025", subjectType, avgRank);
                    if (score == null) {
                        logger.warn("未找到位次为{}，科目类型为{}的对应分数", avgRank, subjectType);
                        continue;
                    }
                    // 设置预测排名和分数
                    record.setYcPaiming(avgRank);
                    record.setYcScore(score);
                    toUpdateRecords.add(record);
                } catch (Exception e) {
                    logger.error("处理记录时发生异常，记录ID：{}", record.getId(), e);
                }
            }



            // 批量更新
            if (!CollectionUtils.isEmpty(toUpdateRecords)) {
                int updatedCount = recruitMajorInfoService.batchUpdatePrediction(toUpdateRecords);
                logger.info("成功更新{}条记录", updatedCount);
            }

        } catch (Exception e) {
            logger.error("执行招生专业信息预测排名和分数计算任务时发生异常", e);
        }

        logger.info("招生专业信息预测排名和分数计算任务执行完成");
    }

    /**
     * 计算平均位次
     */
    private Integer calculateAverageRank(List<HistoricalAdmissionScoreEntity> historicalScores) {
        Map<String, Integer> yearRankMap = new HashMap<>();
        // 按年份分组
        for (HistoricalAdmissionScoreEntity score : historicalScores) {
            if (score.getLowRank() != null) {
                yearRankMap.put(score.getYear(), score.getLowRank());
            }
        }
        // 如果2023和2024年都有值，则计算平均值
        if (yearRankMap.containsKey("2023") && yearRankMap.containsKey("2024")) {
            return (yearRankMap.get("2023") + yearRankMap.get("2024")) / 2;
        }
        // 如果只有2024年的值，则取2024年的值
        if (yearRankMap.containsKey("2024")) {
            return yearRankMap.get("2024");
        }
        // 如果只有2023年的值，则取2023年的值
        if (yearRankMap.containsKey("2023")) {
            return yearRankMap.get("2023");
        }
        // 都没有则返回null
        return null;
    }

    /**
     * 获取科目类型
     */
    private String getSubjectType(RecruitMajorInfoEntity record) {
        // 根据物理或历史科目要求确定科目类型
        if (record.getPhysics() != null && record.getPhysics() == 1) {
            return "物理";
        } else if (record.getHistory() != null && record.getHistory() == 1) {
            return "历史";
        }
        // 默认返回物理
        return "物理";
    }

    /**
     * 获取文理
     */
    private String getWenLi(RecruitMajorInfoEntity record) {
        // 根据物理或历史科目要求确定科目类型
        if (record.getPhysics() != null && record.getPhysics() == 1) {
            return "理科";
        } else if (record.getHistory() != null && record.getHistory() == 1) {
            return "文科";
        }
        // 默认返回物理
        return "理科";
    }


    /**
     * 计算专业组平均位次
     */
    private Integer calculateSchoolCodeAverageRank(RecruitMajorInfoEntity historicalScores,String nature) {
        // 根据学校ID和专业查询专业组平均位次
        Integer avgRank = historicalAdmissionScoreService.findSchoolCodeAverageRank(historicalScores.getSchoolId(), historicalScores.getSchoolCode(),nature);
        if (avgRank == null) {
            logger.warn("无法计算学校ID为{}，专业为{}的专业组平均排名", historicalScores.getSchoolId(), historicalScores.getPro());
            return null;
        }
        // 返回专业组平均位次
        return avgRank;
    }

}
